package com.record.shdx;

import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import com.record.utils.MD5;
import com.record.utils.RecUtils;
import localhost.dcms.webservice.QueryRecord.QueryRecord;
import localhost.dcms.webservice.QueryRecord.QueryRecordServiceLocator;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

public class SHDXRecUtils extends HttpServlet {
    private static final Log log = LogFactory.getLog(SHDXRecUtils.class);
    private static JSONObject rec_Config = new JSONObject();
    private static String url = "";
    private static String hccurl = "";
    private static String passwordasmd5 = "";
    private static String sessionidsplit = "";
    private static String hex2decimal = "";
    private static String amrconvertcmd = "";
    private static String urlreplace = "";

    // SHDX(上海电信)录音平台获取(2112200001)
    public static String doSHDXRecord(JdbcTemplate jt, HttpServletResponse response, String entId, String recdata, String multimode) {
        log.debug("SHDX(上海电信)录音平台获取(1909090002) recordPath:" + recdata);

        // 初始化返回
        String res_RecordStr = "";

        try {

            // 初始化参数
            rec_Config = KHUtil.SFIsNull(rec_Config.toString()) ? JSONObject.fromObject(KHDBConfig.getParamConfig(jt, "REC_CFG-" + entId)) : rec_Config;

            url = KHUtil.GetSFJV(rec_Config, "url");
            hccurl = KHUtil.GetSFJV(rec_Config, "hccurl");

            passwordasmd5 = KHUtil.GetSFJV(rec_Config, "passwordasmd5");
            sessionidsplit = KHUtil.GetSFJV(rec_Config, "sessionidsplit");
            hex2decimal = KHUtil.GetSFJV(rec_Config, "hex2decimal");
            urlreplace = KHUtil.GetSFJV(rec_Config, "urlreplace");

            amrconvertcmd = KHUtil.GetSFJV(rec_Config, "amrconvertcmd");

            if (recdata != null) {
                if (!recdata.startsWith("cdrkey|")) {
                    log.debug("SHDX(上海电信)录音平台 CCOD");
                    String[] datas = recdata.split("\\|");
                    if (datas.length == 4) {
                        try {
                            String recurl = getRecURL(datas);
                            log.debug("SHDX(上海电信)录音平台 返回录音URL:" + recurl);

                            // 处理URL中需要替换的内容
                            if (!KHUtil.isNull(urlreplace)) {
                                String[] pair = urlreplace.split("\\|");
                                if (pair.length == 2)
                                    recurl = recurl.replace(pair[0], pair[1]);
                                else {
                                    log.error("配置的URL中需要替换的内容错误, url replace is invalid");
                                }
                            }

                            // 多录音模式 或直接返回录音URL
                            if (multimode.equals("1")) {
                                if (!recurl.contains("<recordFiles>")) {
                                    recurl = "<recordFiles><recordFile><recordName>" + recurl + "</recordName></recordFile></recordFiles>";
                                }
                                log.debug("return string to client:" + recurl);
                                res_RecordStr = recurl;
                                return res_RecordStr;

                            }

                            if (recurl.toLowerCase().startsWith("http://")) {
                                // 配置录音转换
                                if (!KHUtil.isNull(amrconvertcmd)) {
                                    RecUtils.ConvertAmrAudio(jt, response, entId, recurl);
                                    return "";
                                }
                                response.sendRedirect(recurl);
                                return "";

                            }

                            log.error("invalid http url:" + recurl);
                            throw new RuntimeException("invalid http url:" + recurl);
                        } catch (Exception e) {
                            res_RecordStr = "获取SHDX(上海电信)录音平台录音CCOD 异常:" + e.getMessage();
                            log.error(res_RecordStr, e);
                        }

                    } else {
                        log.debug("fetch hcc record");
                        recdata = recdata.replace("|", "=");
                        log.debug("url:" + hccurl + recdata);
                        URL url = new URL(hccurl + recdata);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("GET");
                        con.setUseCaches(false);
                        con.connect();
                        try {
                            InputStream in = con.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                            String xml = "";
                            StringBuilder b = new StringBuilder();
                            String line;
                            while ((line = reader.readLine()) != null) {
                                b.append(line);
                            }

                            xml = b.toString();

                            log.debug("receive xml:" + xml);
                            try {
                                Document doc = DocumentHelper.parseText(xml);
                                log.debug("xml parsed");
                                List nodes = doc.selectNodes("//record");
                                Iterator it = nodes.iterator();
                                while (it.hasNext()) {
                                    Node node = (Node) it.next();
                                    Element element = (Element) node;
                                    Attribute attr = element.attribute("rec");
                                    if ((attr != null) && (!attr.getStringValue().equals(""))) {
                                        log.debug("redirect to " + attr.getStringValue());
                                        response.sendRedirect(attr.getStringValue());
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                res_RecordStr = "获取SHDX(上海电信)录音平台录音HCC XML异常:" + e.getMessage();
                                log.error(res_RecordStr, e);
                            }

                        } finally {
                            con.disconnect();
                        }
                    }
                } else {
                    res_RecordStr = "获取SHDX(上海电信)录音平台录音错误:recdata is invalid";
                    log.error(res_RecordStr);
                }
            } else {
                res_RecordStr = "获取SHDX(上海电信)录音平台录音错误:recdata is null";
                log.error(res_RecordStr);
            }
        } catch (Exception e) {
            res_RecordStr = "获取SHDX(上海电信)录音平台录音异常:" + e.getMessage();
            log.error(res_RecordStr, e);
        }

        return res_RecordStr;

    }

    // SHDX(上海电信-历史)录音平台获取(1912110002)
    public static String doSHDXRecord2(JdbcTemplate jt, HttpServletResponse response, String entId, String recData, String multimode) {
        return doSHDXRecord2(jt, response, entId, recData, multimode);
    }

    // SHDX(上海电信-历史)录音平台获取录音地址
    public static String getRecURL(String[] datas) throws Exception {
        QueryRecordServiceLocator locator = new QueryRecordServiceLocator();
        locator.setQueryRecordEndpointAddress(url);
        QueryRecord service = locator.getQueryRecord(new URL(url));

        String md5password = datas[3];
        if (passwordasmd5.equalsIgnoreCase("true")) {
            md5password = MD5.getstring(datas[3]).toUpperCase();
            log.debug("MD5 password is " + md5password);
        }

        String sessionid = datas[1];
        if ((!sessionidsplit.equals("")) && (sessionid.contains(sessionidsplit))) {
            sessionid = sessionid.substring(0, sessionid.indexOf(sessionidsplit));
        }

        if (hex2decimal.equalsIgnoreCase("true")) {
            sessionid = String.valueOf(Long.parseLong(sessionid, 16));
        }
        log.debug("sessionid is " + sessionid);

        String recurl = service.queryRecordAddr(datas[0], datas[2], md5password, sessionid);
        log.debug("recurl is " + recurl);
        return recurl;
    }

}